package com.mate.cloud.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @description ${description}
 * @author cong zhi
 * @email  448341911@qq.com
 * @createDate   2023/3/20 15:50
 * @version: v1.0
 */
@Component
public class LearnWebMvcBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(429);
        PrintWriter out = response.getWriter();
        if (e instanceof FlowException) {
            out.println("Hello flow limit.");
            out.flush();
            out.close();
        } else if (e instanceof DegradeException) {
            out.println("Hello degrade.");
            out.flush();
            out.close();
        }
    }
}
